package com.baor.service.impl;

import com.baor.dao.AdminDao;
import com.baor.dao.MenuDao;
import com.baor.domain.AdminVo;
import com.baor.domain.MenuVo;
import com.baor.seacurity.TokenService;
import com.baor.service.AdminService;
import com.baor.utils.AjaxResult;
import com.baor.utils.MD5Utils;
import com.baor.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.PublicKey;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service

public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MenuDao menuDao;
    @Value("${sys.default.pwd}")
    private String defaultPwd;
//    @Autowired
//    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;
    public static AdminVo vo = null;

//    @Autowired
//    private PasswordEncoder passwordEncoder;

    @Override
    public AjaxResult<?> login(AdminVo userVo) {
//        System.out.println("login-info:"+userVo);
//        Authentication authentication = null;
//        try {
//            authentication = authenticationManager.authenticate(
//                    new UsernamePasswordAuthenticationToken(userVo.getAdminAccount(),userVo.getAdminPassword())
//            );
//        } catch (RuntimeException ex) {
//            System.out.println("出异常了");
//            ex.printStackTrace();
//            return AjaxResult.error();
//        }
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String requestPath = attributes.getRequest().getRequestURI();

            Map<String,Object> res = new HashMap<>();
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        userVo.setAdminPassword(MD5Utils.md5(userVo.getAdminPassword()));
        List<AdminVo> adminVoList = this.adminDao.selectUserByUserNameAndSite(userVo);
        List<AdminVo> adminVos = this.adminDao.selectUserByUserName(userVo);
        if(adminVos != null && !adminVos.isEmpty()){
            if(adminVoList != null && !adminVoList.isEmpty()){
                vo = adminVoList.get(0);
            }else{
                return AjaxResult.error("当前管理员未分配站点");
            }
        }else{
            return AjaxResult.error("登陆失败,信息错误");
        }


        if(vo.getAdminStatus().equals("正常")){
            //登陆时更换最后登录时间
            LocalDateTime currentDateTime = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = currentDateTime.format(formatter);
            Map<String,Object> params = new HashMap<>();
            params.put("lastTime",formattedDateTime);
            vo.setLastTime(formattedDateTime);
            params.put("adminId",vo.getAdminId());
            int updateTime = this.adminDao.updateTime(params);
            String token = tokenService.createToken(vo);
            redisUtil.setValue("userAccount:"+vo.getAdminAccount(),vo);
            redisUtil.setValue("token:"+vo.getAdminAccount(),token);
            res.put("authorization",token);
            res.put("user", vo);
            return AjaxResult.success(res);
        }else{
            return  AjaxResult.error("当前用户处于禁用状态");
        }

//        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, loginUser.getPassword(), loginUser.getAuthorities());
//        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);


    }

    @Override
    public AjaxResult<?> list(Map<String,Object> params) {
        if(params.containsKey("pageIndex")&&params.containsKey("pageSize")){
            int pageIndex= (int) params.get("pageIndex");
            int pageSize = (int) params.get("pageSize");
            params.put("pageIndex",(pageIndex - 1) * pageSize);
            List<AdminVo> adminVoList = this.adminDao.list(params);
            Map<String,Object> res = this.adminDao.findPageCount(params);
            res.put("adminList",adminVoList);
            return AjaxResult.success(res);
        }else{
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult<?> insert(AdminVo adminVo)  {
            InetAddress localHost = null;
            try {
                localHost = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }

            adminVo.setAdminIp(String.valueOf(localHost));
            if(adminVo.getAdminPassword() != null){
                adminVo.setAdminPassword(MD5Utils.md5(adminVo.getAdminPassword()));
            }
            if(adminVo.getLastTime() == null){
                LocalDateTime currentDateTime = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedDateTime = currentDateTime.format(formatter);
                adminVo.setLastTime(String.valueOf(formattedDateTime));
            }
            Map<String,Object> params = new HashMap<>();
            params.put("adminAccount", adminVo.getAdminAccount());
            List<AdminVo> adminVoList = this.adminDao.selectUserByUserName(adminVo);

            System.out.println(adminVoList);
            if(adminVoList != null && !adminVoList.isEmpty()){
                return AjaxResult.error("账号已存在,请重新输入账号");
            }else{
                int row = adminDao.insert(adminVo);
                int adminId = adminDao.findAdminId();
                adminVo.setAdminId((long) adminId);
                int row2 =adminDao.insertCenter(adminVo);
                if(row>0 && row2>0){
                    return AjaxResult.success();
                }else{
                    return AjaxResult.error();
                }
            }

    }
    @Override
    public AjaxResult<?> delete(int adminId) {
        if(adminId == 1){
            return AjaxResult.error("超管不能删除");
        }else{
            int row = adminDao.deleteById(adminId);
            if(row>0){
                return AjaxResult.success();
            }else{
                return AjaxResult.error();
            }
        }

    }

    @Override
    public AjaxResult<?> update(AdminVo adminVo) {
        int row = adminDao.updateById(adminVo);
        if(row>0){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult<?> shopAdmin(int adminId) {
        if(adminId == 1){
            return AjaxResult.error("超管不能禁用");
        }else{
            int shop = this.adminDao.shopAdmin(adminId);
            if(shop>0){
                return AjaxResult.success();
            }else{
                return AjaxResult.error();
            }
        }

    }

    public static AdminVo getVo(){
        return vo;

    }
}
